import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { articleSearchService, articleAllService, articleCategoryAllService, articleDetailService, AllTagService } from '@/apis/article.js'

export const useArticleStore = defineStore('article', () => {
  const articles = ref([])
  const categorys = ref([])
  const tags = ref([])
  const tagIds = ref([])
  const tagNames = ref([])
  const pageNum = ref(1)
  const total = ref(0)
  const pageSize = ref(10)
  const categoryId = ref('')
  const state = ref('')
  const search = ref('')
  const allArticles = ref([])

  // 搜索结果（有则显示搜索结果，无则显示全部文章）
  // 本地过滤已弃用，改用API过滤

  // 获取分页数据
  async function fetchArticles() {
    const params = {
      pageNum: pageNum.value,
      pageSize: pageSize.value,
      categoryId: categoryId.value || null,
      state: state.value || null,
      tagIds: tagIds.value || null,
      tagNames: tagNames.value || null
      // tags: tags.value || null
    }
    let result
    if (search.value) {
      result = await articleSearchService({
        ...params,
        query: search.value
      })
    } else {
      result = await articleAllService(params)
    }
    total.value = result.data.total
    articles.value = result.data?.items || [] // 添加空数组回退

    // // 给文章添加分类名称和文章数量
    // articles.value.forEach(article => {
    //   const category = categorys.value.find(c => c.id === article.categoryId)
    //   if (category) {
    //     article.categoryName = category.categoryName
    //     article.articleCount = category.articleCount
    //   }
    // })
  }

  // 获取分类列表
  async function fetchCategories() {
    const result = await articleCategoryAllService()
    categorys.value = result.data
  }

  //获取标签列表
  async function fetchTags() {
    const result = await AllTagService()
    tags.value = result.data
  }

  // 获取全部文章（不分页并按时间排序，用于首页展示最新文章）
  async function fetchAllArticles() {
    // 设置一个大的pageSize，一次性获取所有文章
    const result = await articleAllService({ pageSize: 1000, pageNum: 1 }) // Fetch a large number of articles
    // 按时间排序
    allArticles.value = result.data.items.sort((a, b) =>
      new Date(b.createTime) - new Date(a.createTime)
    )
  }

  // 获取文章详情
  async function fetchArticleById(id) {
    const result = await articleDetailService(id)
    return result.data
  }

  // 监听分页大小和当前页
  function onSizeChange(size) {
    pageSize.value = size
    fetchArticles()
  }

  // 监听当前页
  function onCurrentChange(num) {
    pageNum.value = num
    fetchArticles()
  }

  return {
    articles,
    categorys,
    tags,
    tagIds,
    tagNames,
    pageNum,
    total,
    pageSize,
    categoryId,
    state,
    search,

    fetchTags,
    fetchArticles,
    fetchCategories,
    onSizeChange,
    onCurrentChange,
    fetchArticleById,
    allArticles,
    fetchAllArticles
  }
})

